package com.stn.zjx.givingtreasure.activity.bi;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.scan.WalletScanActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.GetEthBalanceDomain;
import com.stn.zjx.givingtreasure.domain.GetEthChargeDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.EthTransferEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.ScanResultEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.service.WalletUserService;
import com.stn.zjx.givingtreasure.table.WalletUser;
import com.vondear.rxtools.RxActivityTool;
import com.warkiz.widget.IndicatorSeekBar;
import com.warkiz.widget.OnSeekChangeListener;
import com.warkiz.widget.SeekParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BTransferActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.user_iv)
    RelativeLayout userIv;
    @BindView(R.id.address_edit)
    EditText addressEdit;
    @BindView(R.id.money_edit)
    EditText moneyEdit;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.hpv)
    IndicatorSeekBar hpv;
    @BindView(R.id.sum)
    TextView sum;
    @BindView(R.id.scan_bt)
    RelativeLayout scanBt;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.transfer_bt)
    ButtonBgUi transferBt;
    private String address = "";
    private String tokenAddress = "";
    private String tokenSymbol = "";
    private int tokenDecimal = 0;

    public String gasLimit = "80000";
    private String maxGasPrice = "0";
    private String minGasPrice = "0";
    private String sendAddress = "";
    String gasprice = "0";

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ScanResult(ScanResultEvent event) {
        switch (event.flag) {
            case ScanResultEvent.Wallet_Transfer:
                addressEdit.setText(event.data);
                addressEdit.setSelection(addressEdit.getText().length());
                break;
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initComponent() {
        scanBt.setVisibility(View.VISIBLE);
        sendAddress = getIntent().getStringExtra("sendAddress");
        if (!TextUtils.isEmpty(sendAddress)) {
            addressEdit.setText(sendAddress);
            addressEdit.setSelection(addressEdit.getText().length());
        }
        address = getIntent().getStringExtra("address");
        tokenAddress = getIntent().getStringExtra("tokenAddress");
        tokenSymbol = getIntent().getStringExtra("tokenSymbol");
        tokenDecimal = getIntent().getIntExtra("tokenDecimal", 18);
        actionTitle.setText(tokenSymbol + getString(R.string.transfer));

        hpv.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                String news = new DecimalFormat("0.00000000").format(((double) seekParams.progress / (double) 100000));
                String mins = new DecimalFormat("0.00000000").format(Double.parseDouble(minGasPrice) / Math.pow(10, 18));
                gasprice = new DecimalFormat("0.00000000").format(Double.parseDouble(news) + Double.parseDouble(mins));
                sum.setText(gasprice + " ether");
            }

            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {

            }
        });

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b_transfer);
        ButterKnife.bind(this);
        initComponent();
        get_eth_charge();
    }

    @Override
    protected void onStart() {
        super.onStart();
        get_eth_balance(address,tokenAddress,tokenDecimal,tokenSymbol);
    }

    @OnClick({R.id.back_bt, R.id.scan_bt, R.id.transfer_bt})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();

        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.scan_bt:
                bundle.putInt("flag", ScanResultEvent.Wallet_Transfer);
                RxActivityTool.skipActivity(this, WalletScanActivity.class, bundle);
                break;
            case R.id.transfer_bt:
                if (TextUtils.isEmpty(addressEdit.getText().toString())) {
                    showToast(getString(R.string.transfer_address_is_not_null));
                    return;
                }
                if (TextUtils.isEmpty(addressEdit.getText().toString())) {
                    showToast(getString(R.string.transfer_address_is_not_null));
                    return;
                }
                if (TextUtils.isEmpty(moneyEdit.getText().toString())) {
                    showToast(getString(R.string.money_input_is_not_null));
                    return;
                }

                double d = 0;
                try {
                    d = Double.parseDouble(moneyEdit.getText().toString().trim());
                    if (d <= 0) {
                        showToast(getString(R.string.money_input_is_not_null));
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(getString(R.string.money_input_is_not_num));
                    return;
                }
                if (minGasPrice.equals("0") || maxGasPrice.equals("0")) {
                    showToast(getString(R.string.miner_cost_is_not_null));
                    return;
                }
                if (Double.parseDouble(gasprice) <= 0) {
                    showToast(getString(R.string.miner_cost_is_not_null));
                    return;
                }


                initInputPassword();
                break;
        }
    }

    //获取ETH手续费
    public void get_eth_charge() {
        EthNetImpl.get_eth_charge("get_eth_charge",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            GetEthChargeDomain domain = new Gson().fromJson(response.body(), GetEthChargeDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    gasLimit = domain.getData().getGasLimit();
                                    minGasPrice = domain.getData().getMinGasPrice();
                                    maxGasPrice = domain.getData().getMaxGasPrice();
                                    double snow = (Double.parseDouble(maxGasPrice) / Math.pow(10, 18)) - (Double.parseDouble(minGasPrice) / Math.pow(10, 18));
                                    hpv.setMin(0);
                                    hpv.setMax((int) (snow * 100000));
                                    gasprice = new DecimalFormat("0.00000000").format(Double.parseDouble(minGasPrice) / Math.pow(10, 18));
                                    hpv.setProgress(0);
                                    sum.setText(gasprice + " ether");
                                    break;
                            }
                        }

                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            GetEthChargeDomain domain = new Gson().fromJson(response.body(), GetEthChargeDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    gasLimit = domain.getData().getGasLimit();
                                    minGasPrice = domain.getData().getMinGasPrice();
                                    maxGasPrice = domain.getData().getMaxGasPrice();
                                    double snow = (Double.parseDouble(maxGasPrice) / Math.pow(10, 18)) - (Double.parseDouble(minGasPrice) / Math.pow(10, 18));
                                    hpv.setMin(0);
                                    hpv.setMax((int) (snow * 100000));
                                    gasprice = new DecimalFormat("0.00000000").format(Double.parseDouble(minGasPrice) / Math.pow(10, 18));
                                    hpv.setProgress(0);
                                    sum.setText(gasprice + " ether");
                                    break;
                            }
                        }

                    }
                });
    }


    //弹出输入钱包密码
    public void initInputPassword() {
        Dialog dialog = new Dialog(this, R.style.dialog_soft_input);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_input_wallet_password);
        EditText passwordEdit = dialog.findViewById(R.id.password_edit);
        View cancel_bt = dialog.findViewById(R.id.cancel_bt);
        cancel_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        View sure_bt = dialog.findViewById(R.id.sure_bt);
        sure_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                WalletUser db = WalletUserService.getInstance(getApplicationContext())
                        .getWalletUser(address);
                if (db == null) {
                    showToast(getString(R.string.db_error));
                    return;
                }

                tranfer(tokenSymbol,
                        tokenAddress,
                        address,
                        addressEdit.getText().toString().trim(),
                        passwordEdit.getText().toString().trim(),
                        moneyEdit.getText().toString().trim(),
                        tokenDecimal + "",
                        gasprice,
                        gasLimit,
                        contentEdit.getText().toString().trim()
                );

            }
        });
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {

                //   SoftInputUtils.openSoftInput(FirstCreateEthBackUpActivity.this, dialog.getCurrentFocus(), 50);

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                //       SoftInputUtils.closedSoftInput(FirstCreateEthBackUpActivity.this);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                passwordEdit.getText().clear();
            }
        });
        dialog.show();

    }

    //转账
    public void tranfer(
            String symbol,
            String contractAddress,
            String fromAddress,
            String toAddress,
            String walletPassword,
            String value,
            String decimal,
            String gasPrice,
            String gasLimit,
            String extra) {
        EthNetImpl.request_transfer(
                symbol,
                contractAddress,
                fromAddress,
                toAddress,
                walletPassword,
                value,
                decimal,
                gasPrice,
                gasLimit,
                extra,
                "request_transfer", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                        switch (domain.getStatus()) {
                            case BaseApi.REQUEST_SUCCESS_CODE:
                                get_eth_balance(address,tokenAddress,tokenDecimal,tokenSymbol);
                            //    showToast(domain.getMessage());
                                moneyEdit.getText().clear();
                                contentEdit.getText().clear();
                                EthTransferEvent ethTransferEvent=new EthTransferEvent();
                                  ethTransferEvent.flag=EthTransferEvent.TRANSFER_FINISH;
                                  EventBus.getDefault().post(ethTransferEvent);
                                finish();
                                break;
                            default:
                                showToast(domain.getMessage());
                                break;
                        }
                    }
                }

        );


    }

    //获取ETH,代币余额
    public void get_eth_balance(String ethAddress,
                                String ethTokenAddress,
                                Integer ethTokenDecimal,
                                String  ethTokenSymbol
    ){
        EthNetImpl.get_eth_balance(ethAddress,ethTokenAddress,ethTokenDecimal,ethTokenSymbol,ethAddress+ethTokenAddress + "_get_eth_balance",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response.isSuccessful()&&!isFinishing()){
                            GetEthBalanceDomain domain=new Gson().fromJson(response.body(),GetEthBalanceDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    priceTv.setText(getString(R.string.current_balance)+" "+domain.getData().getBalance());
                                    break;
                                default:
                                    priceTv.setText(getString(R.string.current_balance)+" 0");
                                    break;
                            }
                        }

                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if(response.isSuccessful()&&!isFinishing()){
                            GetEthBalanceDomain domain=new Gson().fromJson(response.body(),GetEthBalanceDomain.class);
                            switch (domain.getStatus()){
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    priceTv.setText(getString(R.string.current_balance)+" "+domain.getData().getBalance());
                                    break;
                                default:
                                    priceTv.setText(getString(R.string.current_balance)+" 0");
                                    break;
                            }
                        }

                    }
                });
    }
}
